package com.tsj.model.controller;

import com.tsj.model.model.input.ImportExcelParameterInput;
import com.tsj.model.model.vo.ImportExcelVo;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-10-22 09:22:16
 */
@RestController
@Tag(name = "Import控制器")
@RequestMapping("/import")
@Hidden
public class ImportController {

    @Operation(summary = "导入Excel")
    @PostMapping(value = "/excel", consumes = "multipart/form-data")
    public ResponseEntity<List<ImportExcelVo>> excel(ImportExcelParameterInput input) {
        try {
            System.out.println(input.getName());
            // 读取Excel文件
            XSSFWorkbook workbook = new XSSFWorkbook(input.getFile().getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);

            List<ImportExcelVo> excelVoList = new ArrayList<>();
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    // 跳过表头行
                    continue;
                }
                ImportExcelVo excelVo = new ImportExcelVo();
                boolean allColumnsFilled = true;
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    if (cell == null || cell.getStringCellValue().trim().isEmpty()) {
                        allColumnsFilled = false;
                        break;
                    }
                    // 假设根据列索引设置ExcelVo的字段，根据实际情况调整
                    if (i == 0) {
                        excelVo.setAnimeName(cell.getStringCellValue());
                    } else if (i == 1) {
                        excelVo.setName(cell.getStringCellValue());
                    }
                }
                if (allColumnsFilled) {
                    excelVoList.add(excelVo);
                }
            }
            return new ResponseEntity<>(excelVoList, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>((HttpHeaders) null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
